package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.ChallengeRepository;
import domain.Administrator;
import domain.Challenge;
import domain.Event;

@Service
@Transactional
public class ChallengeService {

	// Managed repository -----------------------------------------------------

	@Autowired
	private ChallengeRepository challengeRepository;

	@Autowired
	private AdministratorService administratorService;

	// Constructors -----------------------------------------------------------

	public ChallengeService() {
		super();
	}

	// Simple CRUD methods ----------------------------------------------------

	public Challenge create(Event e) {
		Administrator a = administratorService.findByPrincipal();
		Assert.notNull(a.getEvents());
		Challenge c = new Challenge();
		c.setEvent(e);
		return c;
	}

	public void save(Challenge c) {
		Assert.notNull(c);
		Assert.isTrue(c.getEvent().getAdministrator().equals(
				administratorService.findByPrincipal()),
				"tried to edit a challenge property of other administrator");
		Assert.isTrue(c.getEvent().getStartMoment().compareTo(new Date()) > 0);
		challengeRepository.save(c);
	}

	public void delete(Challenge c) {
		Assert.notNull(c);
		Assert.isTrue(c.getEvent().getAdministrator().equals(
				administratorService.findByPrincipal()));
		Assert.isTrue(c.getEvent().getStartMoment().compareTo(new Date()) > 0);
		challengeRepository.delete(c);
	}

	public Challenge findOne(int id){
		return challengeRepository.findOne(id);
	}
	
	// Other business methods -------------------------------------------------

	public Collection<Challenge> findChallengesByEvent(Event event) {
		return challengeRepository.findChallengesByEvent(event.getId());
	}
	
	// Form object related methods ---------------------------------------------
	public Boolean itsHacked (Challenge c){
		Boolean res = true;
		
		Challenge persistedOne = challengeRepository.findOne(c.getId());
		if(c.getId()!=0){
		if(c.getEvent()==null || persistedOne.getEvent().equals(c.getEvent()))
			res = false;
		}
		
		if(c.getId()==0)
			res=false;
		return res;
	}
	
}
